﻿CREATE FUNCTION laycapmenuload  
(  
  @MaNhom int
)  
RETURNS   
@bangtam TABLE   
(  
 Lever int,  
 LeverName nvarchar(500)  
)  
AS  
BEGIN  
declare @dem as int  
select @dem=COUNT(*) from QuanTri_PhanNhomMenu WHere MaNhomMenuND=@MaNhom
if(@dem>0)  
begin  
declare @bangtamfinal TABLE   
(  
 Lever int  
)  
declare @maxmenu as int  
select @maxmenu= MAX(Cap)+1 from QuanTri_PhanNhomMenu WHere MaNhomMenuND=@MaNhom 
if(@maxmenu<5)
begin
insert into @bangtamfinal(Lever) values(@maxmenu)  
end
insert into @bangtamfinal(Lever)  
select distinct Cap from QuanTri_PhanNhomMenu WHere MaNhomMenuND=@MaNhom  
insert into @bangtam (Lever,LeverName)  
select Lever,N'Menu Cấp '+cast(Lever as nvarchar(50)) as LeverName  from @bangtamfinal order by Lever  
  
  
end  
else  
begin  
insert into @bangtam (Lever,LeverName)values(0,N'Menu Cấp 0')  
end  
--select * from Thuan_Menu  
  
   
 RETURN   
END  